import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'js_bridge.dart';

/// 日志输出
var logger = Logger();

class WebViewPage extends StatefulWidget {
  const WebViewPage({Key? key}) : super(key: key);

  @override
  WebviewPageState createState() => WebviewPageState();
}

class WebviewPageState extends State<WebViewPage> {
  late String _htmlContent;
  // JS交互桥接对象
  final JSBridge _jsBridge = JSBridge();

  /// webView加载进度
  double _progress = 0;

  /// webView控制对象
  WebViewController controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setBackgroundColor(const Color(0x00000000));

  @override
  void dispose() {
    // 释放资源
    logger.i("释放资源");
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    _setWebViewController();

    _jsBridge.messageExecutor = controller.runJavaScript;

    // 注册getToken事件， JS调用时会触发
    _jsBridge.register("getToken", (data, callback) {
      logger.i("getToken 接收数据：$data");
      // 回调给JS
      logger.i("发送数据：你看看");
      callback("你看看");
    });

    _jsBridge.register("testCallback", (data, callback) {
      logger.i("testCallback 接收数据:$data");
      logger.i("testCallback JS已收到回调,这里是JS收到回调后发出来的。");
    });

    //
    _jsBridge.register("testUserInfoCallBack", (data, callback) {
      logger.i("testUserInfoCallBack 接收数据:$data");
      logger.i("testUserInfoCallBack JS已收到回调,这里是JS收到回调后发出来的。");
    });

    // 在3秒后执行
    Future.delayed(const Duration(seconds: 3), () {
      _loadHtmlFile();
    });
  }

  // 加载测试HTML
  Future<void> _loadHtmlFile() async {
    // 加载html
    const String htmlPath = 'assets/html/index_air.html';
    _htmlContent = await rootBundle.loadString(htmlPath);
    controller.loadHtmlString(_htmlContent);
    controller.loadRequest(Uri.dataFromString(
      _htmlContent,
      mimeType: 'text/html',
      encoding: Encoding.getByName('utf-8'),
    ));
    // controller.loadFlutterAsset(htmlPath);
  }

  /// 设置webView控制器
  void _setWebViewController() {
    // 设置 JavaScriptChannel 接收JS传递过来的数据
    controller.addJavaScriptChannel(JSBridge.name,
        onMessageReceived: (JavaScriptMessage message) {
      logger.i(message.message);
      _jsBridge.receiverMessage(message.message);
    });

    controller.setNavigationDelegate(NavigationDelegate(
      onProgress: (int progress) {
        // setState(() {
        //   _progress = progress / 100;
        // });
      },
      onPageStarted: (String url) {
        logger.i(url);
      },
      onPageFinished: (String url) {
        // 注入js,处理相关Navtive <->  JS 交互
        _jsBridge.injectBridgeJS(controller);

        // 在3秒后执行,调用JS操作
        Future.delayed(const Duration(seconds: 3), () {
          var data = {"userName": "滴滴"};
          logger.i(" userInfo 发送数据：$data");
          // userInfo 为JS中注册在bridge中的函数
          _jsBridge.call("userInfo", {"userName": "滴滴"});
        });
      },
      onWebResourceError: (WebResourceError error) {
        logger.i("error = $error");
      },
      /*  onNavigationRequest: (NavigationRequest request) {
          if (request.url.startsWith('https://www.youtube.com/')) {
            // 阻止路由替换
            return NavigationDecision.prevent;
          }
          // 允许路由替换
          return NavigationDecision.navigate;
        },
       */
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          Align(
            alignment: Alignment.topCenter,
            child: _progress != 1.0
                ? LinearProgressIndicator(
                    value: _progress,
                    valueColor: const AlwaysStoppedAnimation<Color>(
                        Colors.blue), //Colors.green,
                    backgroundColor: const Color(0xFFFFFFFF))
                : null,
          ),
          Expanded(
            child: Container(
              alignment: Alignment.center,
              color: const Color(0xFFFFFFFF),
              child: WebViewWidget(
                key: UniqueKey(),
                controller: controller,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
